package com.jxtti.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.jxtti.entity.ArticleList;
import com.jxtti.model.User;
import com.jxtti.service.ArticleListService;
import com.jxtti.utils.AuthUtil;
import com.jxtti.utils.ExceptionUtil;
import com.jxtti.utils.ImgUtil;
import com.jxtti.utils.StringUtil;



@Controller
@RequestMapping("/ArticleList") 
public class ArticleListController {
	private final static Logger log= Logger.getLogger(ArticleListController.class);
	
	@Autowired //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private ArticleListService  articleListService; 
	
	@InitBinder  //初始化数据的时候，进行数据类型转换，String类型转为Date类型
    public void initBinder(WebDataBinder binder) {     
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");     
        dateFormat.setLenient(false);     
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));//true:���������ֵ��false:����Ϊ��ֵ 
    }
	
	// 左侧文章类目树
	@RequestMapping(value = "/listInterfaceTree")
	@ResponseBody
	public ModelAndView listInterfaceTree(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
			data.put("type", "0");
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/LeftTreeArticleCy.jsp");	
		return mav;
	}
	
	// 投稿统计 左侧 组织架构树
	@RequestMapping(value = "/chartOrgTree")
	@ResponseBody
	public ModelAndView chartOrgTree(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {			
			mav.addObject("data", data);
			com.jxtti.model.User userInfo = com.jxtti.utils.AuthUtil.getUserInfo(request);
			if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非超管
				mav.setViewName("/pages/Admin/Site/AuditArticle/ChartAuditArticle.jsp");
			}else{
				mav.setViewName("/pages/Admin/Site/Article/LeftTreeOrg.jsp");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	
		
	@RequestMapping(value = "/listInterface")
	@ResponseBody
	public ModelAndView listInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/ArticleList.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	//投稿审核
	@RequestMapping(value = "/listInterfaceAudit")
	@ResponseBody
	public ModelAndView listInterfaceAudit(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);			
			mav.setViewName("/pages/Admin/Site/AuditArticle/AuditArticleList.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	

	/**
	 *  <!--角色列表 分页     -->
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/list", method = RequestMethod.POST) 
	@ResponseBody
	public Map<String, Object>  Userlist(@RequestParam Map<String, Object> data,  ArticleList articleList, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		Map<String, Object> result = new HashMap<String, Object>();				
		//判断是否超级管理员		
		User userInfo = AuthUtil.getUserInfo(request);
		//noAdmin 管理员是否失效
		if(data.get("noAdmin")==null){
			if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非管理员
				data.put("fk_orgId",userInfo.getOrgId().toString()); //非管理员 加上权限				
			}
		}else if(data.get("noAdmin")!=null && data.get("noAdmin").equals("yes")){ 		 
			if(userInfo.getRoleId()!=com.jxtti.utils.Constants.AdminRole){//非超管
				data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限				
			}
		}
		if (data.get("categoryID")!=null&&!data.get("categoryID").equals("")) {
			String[]  categorys=data.get("categoryID").toString().split(",");				
			for(int i=0;i<categorys.length;i++ ){
				categorys[i] = categorys[i].replaceAll(categorys[i],"'" + categorys[i] + "'");			
			}			
			String cats=StringUtils.join(categorys, ",");		
			data.put("categoryID",cats);	 
		}	
		
		if (data.get("fk_orgId")!=null&&!data.get("fk_orgId").equals("")) {
			String[]  orgIds=data.get("fk_orgId").toString().split(",");				
			for(int i=0;i<orgIds.length;i++ ){
				orgIds[i] = orgIds[i].replaceAll(orgIds[i],"'" + orgIds[i] + "'");			
			}			
			String cats=StringUtils.join(orgIds, ",");		
			data.put("fk_orgId",cats);	 
		}		
				
		//判断是否有时间 ，默认是今天
		if ((data.get("startTime")==null||data.get("startTime").equals(""))&&(data.get("endTime")==null||data.get("endTime").equals(""))) {				
			Date date =new Date();			
			SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");//完整的时间			
			Calendar c = Calendar.getInstance();  
			if((data.get("type")!=null&&data.get("type").equals("isAudit"))){
				 c.add(Calendar.DATE, - 30); // 投稿审核 是一个月
			}else{
				 c.add(Calendar.DATE, - 7);  
			}
	       
	        Date monday = c.getTime();
		    String preMonday = sdf.format(monday);		        		
			data.put("startTime", preMonday);			
		}
		
		data.put("is_deleted", "0");				
		PageInfo<ArticleList> page = articleListService.list(data);
		result.put("total", page.getTotal());
		result.put("rows", page.getList());
		return result;	
	}
	
	
	/**
	 * 查询所有数据,
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/queryAll")
	@ResponseBody
	public List<ArticleList> queryTCityAQIWriteAll(@RequestParam Map<String, Object> data,
			HttpServletRequest request,	HttpServletResponse response) throws Exception{		
		
		List<ArticleList>  articleList= articleListService.queryAll(data);
		return articleList;
	}
	
	/**
	 * 点击添加跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/addInterface")
	@ResponseBody
	public ModelAndView addInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/ArticleEdit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}	
	
	//我要投稿
	@RequestMapping(value = "/addInterfaceAudit")
	@ResponseBody
	public ModelAndView addInterfaceAudit(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/AuditArticle/AuditArticleEdit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}	
	
	@RequestMapping(value = "/updateInterfaceAudit")
	@ResponseBody
	public ModelAndView updateInterfaceAudit(@RequestParam Map<String, Object> data,
			HttpServletRequest request,ArticleList  articleList,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			articleList = articleListService.queryById(articleList);		
			data.put("articleList", articleList);
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/AuditArticle/AuditArticleEdit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	

	
	/**
	 * 添加或修改数据
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/save")
	@ResponseBody	
	public Map<String,Object> save(@RequestParam Map<String, Object> data,
			ArticleList  articleList, HttpServletRequest request,	HttpServletResponse response) throws Exception{		
		ModelAndView mav = new ModelAndView();
		try {							
			//获得--创建者信息
			User userInfo = AuthUtil.getUserInfo(request);			
			articleList.setCreateUserID(userInfo.getId().toString());
			articleList.setAuthor(userInfo.getRealName());//作者			
			articleList.setFk_orgId(userInfo.getOrgId().toString());			
			articleList.setOrgIdName(userInfo.getOrgName());
			//提取图片地址
			if(articleList.getContents()!=null && !articleList.getContents().equals("")){
				ImgUtil img=new ImgUtil();
				List<String> imagesPath=img.getImageSrc(articleList.getContents());
				articleList.setImagesPath(StringUtils.join(imagesPath.toArray(),","));
				
				articleList.setContents(StringUtil.replaceEnter(articleList.getContents())); // 去除换行符
			}			
			
			if(articleList.getModifyDate()==null){ //如果没有写 编辑时间 则默认当前时间 
		        
				articleList.setModifyDate(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
			}
			
			int exeCount = articleListService.add(articleList);
			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}	
	

	/**
	 * 点击修改跳转到增加界面
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updateInterface")
	@ResponseBody
	public ModelAndView updateInterface(@RequestParam Map<String, Object> data,
			HttpServletRequest request,ArticleList  articleList,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			articleList = articleListService.queryById(articleList);
			
			articleList.setContents(StringUtil.replaceEnter(articleList.getContents()));
			
			data.put("articleList", articleList);
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/ArticleEdit.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}

		
	/**
	 * 修改信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> update(@RequestParam Map<String, Object> data,
			ArticleList  articleList, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			//	User user = AuthUtil.getUserInfo(request);
			//	tSite.setOperPerson(user.getUserName());
			
			//获得--创建者信息
			User userInfo = AuthUtil.getUserInfo(request);			
			articleList.setModifyUserID(userInfo.getId().toString());				
			//提取图片地址
			if(articleList.getContents()!=null && !articleList.getContents().equals("")){
				ImgUtil img=new ImgUtil();
				List<String> imagesPath=img.getImageSrc(articleList.getContents());				
				articleList.setImagesPath(StringUtils.join(imagesPath.toArray(),","));
			}
			if(articleList.getModifyDate()==null){ //如果没有写 编辑时间 则默认当前时间				
				articleList.setModifyDate(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()));
			}
			int exeCount = articleListService.update(articleList);			
			if (exeCount > 0) {
				data.put("success", true);
			} else {
				data.put("success", false);
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	
	/**
	 * 删除信息
	 * 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam Map<String, Object> data,
			HttpServletRequest request,	HttpServletResponse response) {
		try {			
			String[] idArr=data.get("ids").toString().split(",");
			for(String id:idArr){
				ArticleList  articleList=new ArticleList();
				articleList.setId(Integer.parseInt(id));										
				int exeCount=articleListService.delete(articleList);
				if (exeCount > 0) {
					data.put("success", true);
				} else {
					data.put("success", false);
				}
			}
		} catch (Exception e) {
			data.put("success", false);
			data.put("error", ExceptionUtil.createStackTrackMessage(e));
			e.printStackTrace();
		}
		return data;
	}
	
	
	//投稿统计
	@RequestMapping(value = "/chartAudit")
	@ResponseBody
	public ModelAndView chartAudit(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);			
			mav.setViewName("/pages/Admin/Site/AuditArticle/ChartAuditArticle.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}	
	
	//统计分析-- 柱状图
	@RequestMapping(value="/chartAuditList", method = RequestMethod.POST) 
	@ResponseBody
	public List<ArticleList>  chartAuditList(@RequestParam Map<String, Object> data,  ArticleList articleList, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		Map<String, Object> result = new HashMap<String, Object>();				
		//判断是否超级管理员		
		User userInfo = AuthUtil.getUserInfo(request);
		if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非超管
			data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限				
		}
		
		if (data.get("categoryID")!=null&&!data.get("categoryID").equals("")) {
			String[]  categorys=data.get("categoryID").toString().split(",");				
			for(int i=0;i<categorys.length;i++ ){
				categorys[i] = categorys[i].replaceAll(categorys[i],"'" + categorys[i] + "'");			
			}			
			String cats=StringUtils.join(categorys, ",");		
			data.put("categoryID",cats);	 
		}	
		
		if (data.get("fk_orgId")!=null&&!data.get("fk_orgId").equals("")) {
			String[]  orgIds=data.get("fk_orgId").toString().split(",");				
			for(int i=0;i<orgIds.length;i++ ){
				orgIds[i] = orgIds[i].replaceAll(orgIds[i],"'" + orgIds[i] + "'");			
			}			
			String cats=StringUtils.join(orgIds, ",");		
			data.put("fk_orgId",cats);	 
		}		
				
		//判断是否有时间 ，默认是今天
		if ((data.get("startTime")==null||data.get("startTime").equals(""))&&(data.get("endTime")==null||data.get("endTime").equals(""))) {				
			SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");//完整的时间			
			Calendar c = Calendar.getInstance();  		
		    c.add(Calendar.DATE, - 30); // 投稿审核 是一个月			
	        Date monday = c.getTime();
		    String preMonday = sdf.format(monday);		        		
			data.put("startTime", preMonday);			
		}
		List<ArticleList> chart;
				
		
		//paim
		if(data.get("paim")!=null && data.get("paim").equals("yes") ){
			data.put("fk_orgId",null); 	
			chart = articleListService.chartAudit(data);
		}else if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非超管			
			chart = articleListService.chartAuditLine(data); //日期的线图
		}else{			
			chart = articleListService.chartAudit(data);	
		}
		
		return chart;	
	}
		
	// 左侧文
	@RequestMapping(value = "/charArticleCyTree")
	@ResponseBody
	public ModelAndView charArticleCyTree(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			data.put("type", "1");//----- 按照类目统计文章
			mav.addObject("data", data);
			mav.setViewName("/pages/Admin/Site/Article/LeftTreeArticleCy.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	//按类目统计文章
	@RequestMapping(value = "/chartArticleCy")
	@ResponseBody
	public ModelAndView chartArticleCy(@RequestParam Map<String, Object> data,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		try {
			mav.addObject("data", data);			
			mav.setViewName("/pages/Admin/Site/Article/ChartArticleCy.jsp");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	//统计分析-- 柱状图
	@RequestMapping(value="/chartArticleCyList", method = RequestMethod.POST) 
	@ResponseBody
	public List<ArticleList>  chartArticleCyList(@RequestParam Map<String, Object> data,  ArticleList articleList, HttpServletRequest request,
			HttpServletResponse response) throws Exception{		
		Map<String, Object> result = new HashMap<String, Object>();				
		//判断是否超级管理员		
		User userInfo = AuthUtil.getUserInfo(request);
		if(userInfo.getDistrictId()==null || userInfo.getDistrictId().equals("0")){ //非超管
			data.put("fk_orgId",userInfo.getOrgId().toString()); //非超级管理员 加上权限				
		}
		
		if (data.get("categoryID")!=null&&!data.get("categoryID").equals("")) {
			String[]  categorys=data.get("categoryID").toString().split(",");				
			for(int i=0;i<categorys.length;i++ ){
				categorys[i] = categorys[i].replaceAll(categorys[i],"'" + categorys[i] + "'");			
			}			
			String cats=StringUtils.join(categorys, ",");		
			data.put("categoryID",cats);	 
		}	
		
		if (data.get("fk_orgId")!=null&&!data.get("fk_orgId").equals("")) {
			String[]  orgIds=data.get("fk_orgId").toString().split(",");				
			for(int i=0;i<orgIds.length;i++ ){
				orgIds[i] = orgIds[i].replaceAll(orgIds[i],"'" + orgIds[i] + "'");			
			}			
			String cats=StringUtils.join(orgIds, ",");		
			data.put("fk_orgId",cats);	 
		}		
				
		//判断是否有时间 ，默认是今天
		if ((data.get("startTime")==null||data.get("startTime").equals(""))&&(data.get("endTime")==null||data.get("endTime").equals(""))) {				
			SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");//完整的时间			
			Calendar c = Calendar.getInstance();  
			c.add(Calendar.DATE, - 30); 
	        Date monday = c.getTime();
		    String preMonday = sdf.format(monday);		        		
			data.put("startTime", preMonday);			
		}
		List<ArticleList> chart;	
		chart = articleListService.chartArticleCy(data);	
		return chart;	
	}
		
}
